package leetcode.templates.kmp;

import leetcode.helper.HelpDebug;

public class KMP {

	public int kmp(String haystack, String needle) {
		char[] chars1 = haystack.toCharArray();
		char[] chars2 = needle.toCharArray();
		int len1 = chars1.length;
		int len2 = chars2.length;
		int[] p = new int[len2];
		// p中m位置记录数值n,表示[0,n-1]的字符串同[m-n+1,m]字符串相同
		for (int r = 1, l = 0; r < len2 && l < len2; r++) {
			while (l > 0 && chars2[l] != chars2[r]) {
				l = p[l - 1];
			}
			if (chars2[r] == chars2[l]) {
				l++;
			}
			p[r] = l;
		}
		for (int i = 0, j = 0; i < len1 && j < len2; i++) {
			while (j > 0 && chars2[j] != chars1[i]) {
				j = p[j - 1];
			}
			if (chars2[j] == chars1[i]) {
				j++;
			}
			if (j == len2) {
				return i - j + 1;// i-(j-1)
			}
		}
		return len2 == 0 ? 0 : -1;// 当 needle 是空字符串时我们应当返回 0
	}

	public void debug(String haystack, String needle, int e) {
		int r = this.kmp(haystack, needle);
		HelpDebug.compare(e, r);
	}

	public static void main(String[] args) {
		KMP kmp = new KMP();
		String haystack = "hello";
		String needle = "ll";
		int e = 2;
		kmp.debug(haystack, needle, e);
	}
}
